<?php  
/**
 * Accessed from view.php. Moves an item from one place within one container
 * to another place, potentially within a different container. 
 *
 * @copyright &copy; 2006 The Open University
 * @author s.marshall@open.ac.uk
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 * @package resourcepage
 *//** */
 
    // Declare resource page container (nesting) levels
    define('CLEVELS', 3);

    require_once("module_resourcepage.php");
    $DASHBOARD_COUNTER=DASHBOARD_RESOURCEPAGE_EDIT;
    
/**
 * Recursive function to check containeritems subcontainer
 * nesting level is not exceeded
 *
 * Return levels of containeritem subcontainer nesting remaining
 *
 * @param int $cid containeritems table containerid
 * @param int $levelsleft Number of containeritems subcontainer nesting levels left
 * @return int Number of containeritems subcontainer nesting levels left
 *             Note: <0 if containeritems subcontainer nesting levels exceeded
 */
function checklevels($cid, $levelsleft) {
    // Direct SQL may be better if ensure not postgres specific, think about later
    $rs = get_recordset('resourcepage_containeritems', 'containerid', $cid, '',
                        $fields='containerid, itemid, subcontainerid');
    if ($rs && $rs->RecordCount() >= 1) {
        while ($levelsleft >= 0 && !$rs->EOF) {
            if (!empty($rs->fields['subcontainerid'])) {
                $levelsleft--;
                if ($levelsleft >= 0) {
                    $levelsleft = checklevels($rs->fields['subcontainerid'], $levelsleft);
                }
            }
            $rs->MoveNext();
        }
    }
    $rs = NULL;
    return $levelsleft;
}

    $module=module_resourcepage::$inst;
 
    $id=required_param('id',PARAM_INT);    // Course Module ID
    $sourcecontainer=required_param('sourcecontainer',PARAM_INT);
    $sourceitem=required_param('sourceitem',PARAM_ALPHANUM);
    $destcontainer=required_param('destcontainer',PARAM_ALPHANUM);
    $destindex=required_param('destindex',PARAM_INT);
    $scrollpos=optional_param('scrollpos',0,PARAM_INT);
    
    $module->obtain_view_info($id,null,$cm,$course,$resourcepage);
    
    // Security check for editing this page
    $module->verify_edit_action($cm);
    
    // Moving to another page?
    $matches=array();
    if(preg_match('/^otherpage([0-9]+)/',$destcontainer,$matches)) {
        $destpage=$matches[1]; // Page ID
        
        // Get course_modules for other page...
        $module->obtain_view_info(null,$destpage,$destcm,$destcourse,$destresourcepage);
        
        // Security check
        $module->verify_edit_action($destcm);
        
        // Target container
        $destcontainer=$destresourcepage->containerid;
        // Use default position in target, ignore destindex
        $destindex=0;        
    } else {
        $destpage=false;
        $destresourcepage=$resourcepage;
    }
    
        
    // Verify that the target container is editable from the dest resourcepage
    $module->verify_container_editable(
        array($destresourcepage->containerid,$destresourcepage->deletedcontainerid),
        $destcontainer);            
      
    
    // Item or subcontainer? 
    if(strpos($sourceitem,'c')===0) {
        $subcontainer=substr($sourceitem,1);
        
        // Check edit allowed        
        $module->verify_container_subcontainer_editable(        
            array($resourcepage->containerid,$resourcepage->deletedcontainerid),
            $sourcecontainer,$subcontainer);
       // Move - but make sure not moving subcontainer into self
       // At least until sort out javascript
        if ($subcontainer != $destcontainer) {

            // Before move make sure nesting level not exceeded
            // Moving subcontainer into base container or another subcontainer
            // so that's 2 levels used already. Note: Assume Database Integrity
            $levelsleft = CLEVELS - 2;

            // Subtract number of parent containers for dst container
            $cid = $destcontainer;
            while ($levelsleft >= 0 && $cid) {
                if (($cid = get_field('resourcepage_containeritems', 'containerid',
                                      'subcontainerid', $cid))) {
                    $levelsleft--;
                }
            }

            // More checks if levels left and changed by above loop
            if ($levelsleft >= 0 && $levelsleft != (CLEVELS - 2)) {

                // Subtract deepest number of child containers for src container
                $levelsleft = checklevels($subcontainer, $levelsleft);
            }

            // Finally we may be able to move if levels not exceeded
            if ($levelsleft >= 0) {
                $module->move_container_subcontainer($sourcecontainer,$subcontainer,$destcontainer,$destindex);
                       
            	if($destpage!= false) { 
            		   
                	// lets try the update here - but first get all details
                
                	$sql = 'select * from modprefix_containers where id = '.$subcontainer; 
               
                	$rs = $module->do_sql($sql);
                
					// should only be one row return
				
        			while(!$rs->EOF) {
        			
            			$id = $rs->fields['id'];
            			$containertype = $rs->fields['containertype'];
            			$nextupdate = $rs->fields['nextupdate'];
            			$plugininfo = $rs->fields['plugininfo'];
            			$title = $rs->fields['title'];
            			$resourcepageid = $rs->fields['resourcepageid'];
           		
            			// container type is section and it has been moved across resourcepage update to new resourcepage id
            		
            			if( ($containertype == '_section') && ($resourcepageid != $destpage) ) {           			
            			
            			   $module->upd_container($subcontainer, $containertype, $nextupdate, $plugininfo, $title, $destpage);
            			
            			} // endif
            	           	
            			$rs->MoveNext();
            		
        			} // endwhile loop
        			
        			// update any subcontainers below the original container
        			
        			if( ($containertype == '_section') && ($resourcepageid != $destpage) ) { 
        				
        				$module->update_all_containers_details($subcontainer, $destpage);
        				
        			} // endif          			
        			
        		       		
            	} // endif
                
            } else {
                error(get_string('error_nesting_depth','resourcepage'), 
                      'view.php?id='.$cm->id.($scrollpos ? '&scrollpos='.$scrollpos : ''));
            }
        }
    } else {
        // Verify item is within that container and container is within that module
        $module->verify_container_item_editable(
            array($resourcepage->containerid,$resourcepage->deletedcontainerid),
            $sourcecontainer,$sourceitem);
        // Move
        $module->move_container_item($sourcecontainer,$sourceitem,$destcontainer,$destindex);
    }
    
    // Log and return to view
    add_to_log($course->id, "resourcepage", "additem", "view.php?id=$cm->id",
        "Moved item #$sourceitem from #$sourcecontainer to #$destcontainer position #$destindex",$cm->id);
    redirect('view.php?id='.$cm->id.($scrollpos ? '&scrollpos='.$scrollpos : '')); 
?>